const sql = require('../sql/sqlConfig');
const express = require('express');
let router = express.Router();
const pagination = require('../util/page');

router.get('/', function (req, res, next) {
    let option = "SELECT SUM(`total_price`) AS sales_volume FROM `order` WHERE `order_payment_status`=1";
    let SalesVolume = 0;//销售额
    sql.query(option, function (err, rows) {
        if (err) return {errCode:-9999,message:'查询失败'+err};
        if(!rows[0]) return res.send({errCode:9,message:"还没有订单耶"});
        //有订单的情况下
        SalesVolume = rows[0].sales_volume;//销售额
        let getShareCountSql = "SELECT SUM(`money`) AS share_count FROM `commission`";
        let ShareCount = 0;
        sql.query(getShareCountSql, function (err, rows) {
            if (err) return {errCode:-9999,message:'查询失败'+err};
            ShareCount = rows[0]?rows[0].share_count:0;//分销商得到的钱
            let getprincipalCountSql = "select o.`product_id`, sum(o.`num`) as total, p.principal from `order` as o,`product` as p where o.`order_payment_status`=1 and p.`id`=o.`product_id` group by o.`product_id`";
            sql.query(getprincipalCountSql, function (err, rows) {
                if (err) return {errCode:-9999,message:'查询失败'+err};
                let principalCount = 0;//成本
                rows.forEach((val, index, arr) => {
                    principalCount += val.total * val.principal;
                });
                // let profit = (SalesVolume*10-(principalCount*10+ShareCount*10))/10;
                let profit = Math.floor((Subtr(SalesVolume,principalCount+ShareCount)) * 100) / 100;
                let getCashOUtSql = "SELECT SUM(`money`) AS cash_out FROM `cash_out`";
                sql.query(getCashOUtSql, function (err, rows) {
                    if (err) return {errCode:-9999,message:'查询失败'+err};
                    let cash_out = rows[0]?rows[0].cash_out:0;//已经提现的钱
                    let result = {
                        SalesVolume:SalesVolume,
                        principalCount:principalCount,
                        ShareCount:ShareCount,
                        profit:profit,
                        cashOut:cash_out
                    };
                    return res.send({errCode:0,message:"查询成功",result:result})
                })



            });
        });
    });
});
//减法
function Subtr(arg1,arg2){
    var r1,r2,m,n;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
    m=Math.pow(10,Math.max(r1,r2));
    n=(r1>=r2)?r1:r2;
    return ((arg1*m-arg2*m)/m).toFixed(n);
}



module.exports = router;
